package es.unileon.is.finalproyect.userinterface;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import es.unileon.is.finalproyect.auxiliar.Streams;
import es.unileon.is.finalproyect.dbconnection.ApplicationConnection;
import es.unileon.is.finalproyect.exceptions.ApplicationException;
import es.unileon.is.finalproyect.exceptions.CheckException;
import es.unileon.is.finalproyect.users.User;

public class UserPropertiesDialog extends JDialog{
	private JTextField txtPassword;
	private JPasswordField pwdPassword;
	private JTextField txtConfirmPassword;
	private JPasswordField pwdConfirmPassword;
	private JTextField newPassword;
	private JPasswordField newPwdPassword;
	private JTextField txtEmail;
	private JPanel passwordPanel;
	private User _user;
	private JTextField email;
	private ImageLabel _image;
	private byte[] _imageData;
	private int x;
	private int y;
	
	public UserPropertiesDialog(User u, JFrame panel,boolean modal){
		super(panel, modal);
		_user= u;
		setSize(500,600);
		getContentPane().setLayout(new GridLayout(3,1));
		
		passwordPanel = new JPanel(null);
		getContentPane().add(passwordPanel);
		JLabel change = new JLabel("Change Password");
		change.setBounds(30,30,(int)change.getPreferredSize().getWidth(),(int)change.getPreferredSize().getHeight());
		passwordPanel.add(change);
		
		txtPassword = new JTextField();		
		txtPassword.setText("Old Password");
		txtPassword.setBounds(60, 60, (int)txtPassword.getPreferredSize().getWidth(),(int)txtPassword.getPreferredSize().getHeight());
		passwordPanel.add(txtPassword);
		txtPassword.setColumns(10);
		pwdPassword = new JPasswordField();
		txtPassword.addFocusListener(new FocusAdapter() {
			@Override
			public void focusGained(FocusEvent evt1) {
			    ((JTextField)evt1.getSource()).selectAll();
				pwdPassword.setToolTipText("Old Password");
				pwdPassword.setBounds(60, 60, (int)txtPassword.getPreferredSize().getWidth(),(int)txtPassword.getPreferredSize().getHeight());
				passwordPanel.add(pwdPassword);
				passwordPanel.remove(txtPassword);
			}
		});
		
		newPassword = new JTextField();		
		newPassword.setText("New Password");
		x=(int)newPassword.getPreferredSize().getWidth();
		y=(int)newPassword.getPreferredSize().getHeight();
		newPassword.setBounds(60, 100, x,y);
		passwordPanel.add(newPassword);
		newPassword.setColumns(10);
		newPwdPassword = new JPasswordField();
		newPwdPassword.setToolTipText("New Password");
		newPassword.addFocusListener(new FocusAdapter() {
			@Override
			public void focusGained(FocusEvent evt2) {
			    ((JTextField)evt2.getSource()).selectAll();
				newPwdPassword.setBounds(60, 100, x,y);
				passwordPanel.add(newPwdPassword);
				passwordPanel.remove(newPassword);
			}
		});
		
		txtConfirmPassword = new JTextField();		
		txtConfirmPassword.setText("Confirm New Password");
		txtConfirmPassword.setBounds(x+70, 100, (int)txtConfirmPassword.getPreferredSize().getWidth(),(int)txtConfirmPassword.getPreferredSize().getHeight());
		passwordPanel.add(txtConfirmPassword);
		txtConfirmPassword.setColumns(10);
		pwdConfirmPassword = new JPasswordField();
		pwdConfirmPassword.setToolTipText("Confirm New Password");
		txtConfirmPassword.addFocusListener(new FocusAdapter() {
			@Override
			public void focusGained(FocusEvent evt2) {
			    ((JTextField)evt2.getSource()).selectAll();
				pwdConfirmPassword.setBounds(x+70, 100, (int)txtConfirmPassword.getPreferredSize().getWidth()+20,(int)txtConfirmPassword.getPreferredSize().getHeight());
				passwordPanel.add(pwdConfirmPassword);
				passwordPanel.remove(txtConfirmPassword);
			}
		});
		
		JButton changePass = new JButton("Change");
		changePass.setBounds((int)txtConfirmPassword.getPreferredSize().getWidth()+200,80,(int)changePass.getPreferredSize().getWidth(),(int)changePass.getPreferredSize().getHeight());
		passwordPanel.add(changePass);
		changePass.addActionListener(new ActionListener(){			
			public void actionPerformed(ActionEvent evt) {
				if((String.valueOf(pwdConfirmPassword.getPassword()).equals(""))||(String.valueOf(newPwdPassword.getPassword()).equals(""))||(String.valueOf(pwdPassword.getPassword()).equals(" "))){
					JOptionPane.showMessageDialog(getContentPane(), "All password fields must be filled", "Error", JOptionPane.ERROR_MESSAGE);
				}else if(String.valueOf(pwdConfirmPassword.getPassword()).equals(String.valueOf(newPwdPassword.getPassword()))){
					if(_user.changePassword(String.valueOf(newPwdPassword.getPassword()),String.valueOf(pwdPassword.getPassword()))){
						JOptionPane.showMessageDialog(getContentPane(), "Password changed", "Information", JOptionPane.INFORMATION_MESSAGE);
					} else {
						JOptionPane.showMessageDialog(getContentPane(), "Old Password doesn't match", "Error", JOptionPane.ERROR_MESSAGE);
					}
				}			
			}
		});

		JPanel emailPanel = new JPanel(null);
		getContentPane().add(emailPanel);
		JLabel labelEmail = new JLabel("Change email");
		labelEmail.setBounds(30,30,(int)labelEmail.getPreferredSize().getWidth(),(int)labelEmail.getPreferredSize().getHeight());
		emailPanel.add(labelEmail);
		email = new JTextField("New email");
		email.setBounds(60,60,(int)email.getPreferredSize().getWidth()+70,(int)email.getPreferredSize().getHeight());
		emailPanel.add(email);
		email.addFocusListener(new FocusAdapter(){
			public void focusGained(FocusEvent evt){
				((JTextField)evt.getSource()).selectAll();
			}
		});
		JButton changeEmail = new JButton("Change");
		changeEmail.setBounds((int)txtConfirmPassword.getPreferredSize().getWidth()+200,60,(int)changeEmail.getPreferredSize().getWidth(),(int)changeEmail.getPreferredSize().getHeight());
		emailPanel.add(changeEmail);
		changeEmail.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				if(email.getText().equals("")){
					JOptionPane.showMessageDialog(getContentPane(), "Email field is empty", "Error", JOptionPane.ERROR_MESSAGE);
				}
				else try{
					_user.setEmail(email.getText());
					JOptionPane.showMessageDialog(getContentPane(), "Email Changed", "Information", JOptionPane.INFORMATION_MESSAGE);

				} catch (ApplicationException e){
						JOptionPane.showMessageDialog(getContentPane(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		
		JPanel picturePanel = new JPanel(null);
		getContentPane().add(picturePanel);
		JLabel changePictureLabel = new JLabel("Change picture");
		
		int labelWidth = (int) changePictureLabel.getPreferredSize().getWidth();
		int labelHeight = (int) changePictureLabel.getPreferredSize().getHeight();
		int pictureX = 30;
		int pictureY = 30;
		changePictureLabel.setBounds(pictureX, pictureY, labelWidth, labelHeight);
		picturePanel.add(changePictureLabel);
		
		
		byte[] icon = _user.getPicture();
		if(icon == null){
			_image = new ImageLabel(new ImageIcon("img/no_user.jpg"));
		} else {
			_image = new ImageLabel(new ImageIcon(icon));
		}
		
		int imageWidth = (int) _image.getPreferredSize().getWidth();
		int imageHeight = (int) _image.getPreferredSize().getHeight();
		
		_image.setBounds(pictureX+labelWidth+10, pictureY+labelHeight+10, imageWidth, imageHeight);
		picturePanel.add(_image);
		
		JButton browseButton = new JButton("Browse");
		int browseButtonWidth = (int) browseButton.getPreferredSize().getWidth();
		int browseButtonHeight = (int) browseButton.getPreferredSize().getHeight();
		browseButton.setBounds(pictureX+labelWidth-browseButtonWidth, pictureY+labelHeight+10+(imageHeight-browseButtonHeight)/2, browseButtonWidth, browseButtonHeight);
		picturePanel.add(browseButton);
		browseButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				browsePicture();
			}
		});
		
		JButton pictureChangeButton = new JButton("Change");
		int pictureChangeButtonWidth = (int) pictureChangeButton.getPreferredSize().getWidth();
		int pictureChangeButtonHeight = (int) pictureChangeButton.getPreferredSize().getHeight();
		
		pictureChangeButton.setBounds((int)txtConfirmPassword.getPreferredSize().getWidth()+200, pictureY+labelHeight+10+(imageHeight-pictureChangeButtonHeight)/2, pictureChangeButtonWidth, pictureChangeButtonHeight);
		picturePanel.add(pictureChangeButton);
		pictureChangeButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				if(_imageData != null){
					_user.setPicture(_imageData);
					JOptionPane.showMessageDialog(getContentPane(), "Picture changed", "Information" , JOptionPane.INFORMATION_MESSAGE);
				}
			}
		});
		
	}
	
	private void browsePicture(){
		JFileChooser fileChooser=new JFileChooser();
		fileChooser.setFileFilter(new FileFilter(){
			public boolean accept(File f){
				if(f.isDirectory()){
				    return true;
				}
				String nombre = f.getName().toLowerCase();
				if(nombre != null){
				    if(nombre.endsWith(".jpg")){
				    	return true;
				    }
				}
				return false;
		   	}
			public String getDescription(){
				return "jpg image file";
		   }
		});
		
        int seleccion = fileChooser.showOpenDialog(this) ;
        if (seleccion == JFileChooser.APPROVE_OPTION){ 
	        String imageName = fileChooser.getSelectedFile().getAbsolutePath();
			ImageIcon icon = new ImageIcon(imageName);
			if((icon.getIconWidth() == 100) && (icon.getIconHeight() == 100)){
				_image.setIcon(icon);
				try {
					_imageData = Streams.inputStreamToByteArray(new FileInputStream(new File(imageName)));
				} catch (FileNotFoundException e) {
				}
			} else {
				String msg = "Please, choose a picture with 100x100px";
				JOptionPane.showMessageDialog(this, msg, "Error", JOptionPane.ERROR_MESSAGE);
			}
        }
	}
}
